import { useEffect, memo, useState } from 'react'
import { useRequest } from 'ahooks'
import { Invoice, InvoiceStatus, queryInvoiceListOfOrder, InvoiceOfOrder, InvoiceTitleType } from './services'
import { Button, Card, Descriptions, Space, Table, Tag } from 'antd'
import { Access, styled } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants'
import { ColumnsType } from 'antd/es/table'
import dayjs from 'dayjs'

const Container = styled.div`
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;

  .ant-descriptions-item-label {
    align-items: center !important;
  }
`

const InvoiceDetail: React.FC<RoutePageProps> = props => {
  const [data, setData] = useState<Invoice>()
  const [invoiceId, setInvoiceId] = useState<string>()
  const [pagination, setPagination] = useState<PaginationParams>({pageNum: 1, pageSize: 10})
  const { data: list, loading, runAsync } = useRequest(queryInvoiceListOfOrder, {manual: true})

  const columns: ColumnsType<InvoiceOfOrder> = [
    {
      title: '场站名称',
      dataIndex: 'stationName',
      width: 160,
    },
    {
      title: '订单号',
      dataIndex: 'orderId',
      width: 120,
    },
    {
      title: '终端编号',
      dataIndex: 'stubId',
      width: 120,
    },
    {
      title: '充电开始时间',
      dataIndex: 'timeStart',
      width: 160,
      render: val => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '--'
    },
    {
      title: '充电结束时间',
      dataIndex: 'timeEnd',
      width: 160,
      render: val => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '--'
    },
    {
      title: '充电量(度)',
      dataIndex: 'power',
      width: 120,
    },
  ]

  const getStatus = () => {
    switch (data?.status) {
      case InvoiceStatus.待开票: return <Tag color="processing">待开票</Tag>
      case InvoiceStatus.开票成功: return <Tag color="success">已完成</Tag>
      case InvoiceStatus.开票失败: return <Tag color="error">开票失败</Tag>
      case InvoiceStatus.开票中: return <Tag color="processing">开票中</Tag>
      default: return ''
    }
  }

  const downPdf = () => {
    window.open(data?.pdfUrl, '_blank')
  }

  useEffect(() => {
    if (invoiceId) {
      runAsync({
        ...pagination,
        invoiceId,
      })
    }
  }, [pagination])

  useEffect(() => {
    if (props.params.sKey) {
      const _params = sessionStorage.getItem(props.params.sKey.split('___')[0])
      if (_params) {
        const _data = JSON.parse(_params)
        setData(_data)
        runAsync({
          ...pagination,
          invoiceId: _data.recordId,
        })
        setInvoiceId(_data.recordId)
      }
    }
  }, [props.params.sKey])

  return (
    <Container>
      <Card title={<Space>
        <span>发票信息</span>
        {getStatus()}
        <Access accessible={data?.status === InvoiceStatus.开票成功}>
          <a onClick={downPdf}>下载发票</a>
        </Access>
      </Space>}>
        <Descriptions column={3}>
          <Descriptions.Item label='开票主体'>{data ? InvoiceTitleType[data.infoType] : '--'}</Descriptions.Item>
          <Descriptions.Item label='发票抬头'>{data?.infoName || '--'}</Descriptions.Item>
          <Descriptions.Item label='抬头手机号'>{data?.telephone || '--'}</Descriptions.Item>
          <Descriptions.Item label='邮箱'>{data?.email || '--'}</Descriptions.Item>
          {
            data?.infoType === InvoiceTitleType.个人 ? [
              <Descriptions.Item label='车牌号' key='carPlat'>{data?.carPlat || '--'}</Descriptions.Item>,
            ] : [
              <Descriptions.Item label='公司税号' key='companyCode'>{data?.companyCode || '--'}</Descriptions.Item>,
              <Descriptions.Item label='公司地址' key='companyAddress'>{data?.companyAddress || '--'}</Descriptions.Item>,
              <Descriptions.Item label='开户账号' key='bankCode'>{data?.bankCode || '--'}</Descriptions.Item>,
              <Descriptions.Item label='开户行' key='bank'>{data?.bank || '--'}</Descriptions.Item>,
            ]
          }
          <Descriptions.Item label='电费金额(元)'>{data?.electricMoney || '--'}</Descriptions.Item>
          <Descriptions.Item label='服务费金额(元)'>{data?.serviceMoney || '--'}</Descriptions.Item>
          <Descriptions.Item label='开票总额(元)'>{data?.totalMoney || '--'}</Descriptions.Item>
          <Descriptions.Item label='开票人'>{data?.nickname || '--'}</Descriptions.Item>
          <Descriptions.Item label='开票人电话'>{data?.userPhone || '--'}</Descriptions.Item>
          <Descriptions.Item label='开票备注'>{data?.commend || '--'}</Descriptions.Item>
        </Descriptions>
      </Card>
      <Card title='订单信息' extra={<Button onClick={() => setPagination({...pagination, pageNum: 1})} type='primary'>查询</Button>}>
        <Table<InvoiceOfOrder>
          rowKey='orderId'
          loading={loading}
          dataSource={list?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            pageSize: 10,
            showSizeChanger: false,
            total: list?.totalCount || 0,
            onChange: (page, pageSize) => {
              setPagination({
                pageSize,
                pageNum: page === pagination.pageNum ? 1 : page,
              })
            }
          }}
        />
      </Card>
    </Container>
  )
}

export default memo(InvoiceDetail)
